<template>
  <div>
    <div class="title">账号设置</div>
    <!-- <div class="item">
      <div class="itemName">用户头像</div>
      <div class="itemInfo">
        <el-avatar
          :size="40"
          src="http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg"
        >
        </el-avatar>
        <div class="operate">
          <el-button size="small">修改头像</el-button>
        </div>
      </div>
    </div> -->
    <div class="item">
      <div class="itemName">用户名</div>
      <div class="itemInfo">
        <div>{{ userInfo.in_username }}</div>
        <div class="operate">
          <el-button size="small" @click="editUsername">修改用户名</el-button>
        </div>
      </div>
    </div>
    <div class="item">
      <div class="itemName">邮箱验证</div>
      <div class="itemInfo">
        <!-- <div>{{ userInfo.in_mail }}</div> -->
        <div v-if="userInfo.in_mail">
          您验证的邮箱：{{
            hideEmail(userInfo.in_mail)
          }}，若已丢失或停用，请立即更换，避免账号被盗
        </div>
        <div v-else>请绑定邮箱</div>
        <div class="operate">
          <el-button
            size="small"
            @click="commandDialog({ title: '换绑邮箱', result: true })"
            >绑定（换绑）邮箱</el-button
          >
        </div>
      </div>
    </div>
    <div class="item">
      <div class="itemName">手机验证</div>
      <div class="itemInfo">
        <div v-if="userInfo.in_mobile">
          您验证的手机：{{
            hidePhoneNumber(userInfo.in_mobile)
          }}，若已丢失或停用，请立即更换，避免账号被盗
        </div>
        <div v-else>请绑定手机</div>
        <div class="operate">
          <el-button
            size="small"
            @click="commandDialog({ title: '绑定/换绑手机号', result: true })"
            >绑定/换绑手机号</el-button
          >
        </div>
      </div>
    </div>
    <div class="item">
      <div class="itemName">登录密码</div>
      <div class="itemInfo">
        <div>建议使用6-16个字符，可包括大小写字母和数字,初始密码为123456。</div>
        <div class="operate">
          <el-button
            size="small"
            @click="$router.push({ name: 'resetPassword' })"
            >修改密码</el-button
          >
        </div>
      </div>
    </div>
    <div class="item">
      <div class="itemName">实名认证</div>
      <div class="itemInfo">
        <!-- 0未认证1通过2认证中3失败 -->
        <div v-if="userInfo.in_verify == 0">未认证</div>
        <div v-if="userInfo.in_verify == 1">认证成功</div>
        <div v-if="userInfo.in_verify == 2">认证中</div>
        <div v-if="userInfo.in_verify == 3">认证失败</div>
        <div class="operate">
          <el-button size="small" @click="$emit('gotoAuch')"
            >实名认证</el-button
          >
        </div>
      </div>
    </div>

    <SentCodeDialog
      v-for="item in sendCodeState"
      :key="item.title"
      :title="item.title"
      :numTitle="item.numTitle"
      :errorMsg="item.errorMsg"
      :showDialog="item.showDialog"
      @commandDialog="commandDialog"
      @changeNum="changeNum"
      @sendCode="sendCode"
    ></SentCodeDialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import {
  sendEmailCodeApi,
  sendMobileCodeApi,
  changeEmailApi,
  changeMobileNumberApi
} from '@/api/person';
import SentCodeDialog from './component/SentCodeDialog.vue';
import { Message } from 'element-ui';
import { edit_nameApi } from '@/api';
export default {
  data() {
    return {
      // userInfo:{}
      weixinDialogVisible: false,
      wxForm: {
        code: ''
      },
      sendCodeState: [
        {
          title: '换绑邮箱',
          errorMsg: '请输入邮箱',
          numTitle: '邮箱地址',
          showDialog: false,
          requstFiled: 'in_mail',
          sendCodeApi: (data) => sendEmailCodeApi(data),
          changeNumApi: (data) => changeEmailApi(data)
        },
        {
          title: '绑定/换绑手机号',
          errorMsg: '请输入手机号',
          numTitle: '手机号码',
          showDialog: false,
          requstFiled: 'in_mobile',
          sendCodeApi: (data) => sendMobileCodeApi(data),
          changeNumApi: (data) => changeMobileNumberApi(data)
        }
      ]
    };
  },
  props: ['userInfo'],
  components: { SentCodeDialog },
  created() {},
  computed: {
    hidePhoneNumber: () => (phoneNumber) => {
      if (!phoneNumber) return '请绑定手机';
      return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
    hideEmail: () => (email) => {
      if (!email) return '请绑定邮箱';
      const atIndex = email.indexOf('@');
      if (atIndex >= 0) {
        const username = email.substr(0, atIndex);
        const domain = email.substr(atIndex);
        const hiddenUsername =
          username.slice(0, Math.floor(username.length / 2)) + '****';
        return hiddenUsername + domain;
      }
      return email;
    }
  },
  methods: {
    ...mapActions(['ReSetUser']),
    // 更名对话框
    editUsername() {
      this.$prompt('请输入新的用户名', '修改用户名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\u4e00-\u9fa5a-zA-Z0-9\.\-]{2,10}$/,
        inputErrorMessage: '用户名只能包含2-10位中文、字母、数字、小数点'
      })
        .then(({ value }) => {
          edit_nameApi({ in_username: value })
            .then(() => {
              this.$message({
                type: 'success',
                message: '修改成功'
              });
              this.ReSetUser();
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '修改失败,服务器错误'
              });
            });
        })
        .catch(() => {});
    },
    // 控制对话框
    commandDialog(data) {
      const index = this.sendCodeState.findIndex(
        (item) => item.title === data.title
      );
      if (index !== -1) this.sendCodeState[index].showDialog = data.result;
    },
    // 发送验证码
    sendCode(data) {
      const index = this.sendCodeState.findIndex(
        (item) => item.title === data.title
      );
      if (index !== -1)
        this.sendCodeState[index].sendCodeApi(data.num).then((res) => {
          if (res.status === 0) {
            Message.success(res.message);
          } else {
            Message.error(res.message);
          }
        });
    },
    // 改变号码（邮箱 手机号）
    changeNum(data) {
      const index = this.sendCodeState.findIndex(
        (item) => item.title === data.title
      );
      if (index !== -1) {
        const item = this.sendCodeState[index];
        const obj = { code: data.form.code };
        obj.in_userpassword = data.form.in_userpassword;
        obj[item.requstFiled] = data.form.num;

        item.changeNumApi(obj).then((res) => {
          if (res.status === 0) {
            Message.success(res.message);
            this.commandDialog({ title: data.title, result: false });
            window.location.reload();
          } else {
            Message.error(res.message);
          }
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.title {
}

::v-deep .el-button {
  width: 120px;
}

.item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 2px solid #ddd;

  .itemName {
    width: 50px;
    margin-right: 20px;
    min-height: 32px;
    display: flex;
    align-items: center;
  }

  .itemInfo {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;

    .operate {
      width: 120px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .operate-2 {
      width: 120px;
      overflow: hidden;
      display: flex;
      justify-content: space-between;
      align-items: center;

      ::v-deep .el-button {
        width: 45%;
        padding-left: 0;
        padding-right: 0;
      }
    }
  }

  &[data-position='bottom'] {
    border-bottom: none;
    color: red;
  }
}
</style>
